<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="8">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>机构信息</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="handleCreate">新增机构</el-button>
          </div>
          <el-table
            v-loading="loadingTableVisible"
            element-loading-text="拼命加载中"
            element-loading-spinner="el-icon-loading"
            element-loading-background="rgba(0, 0, 0, 0.8)"
            default-expand-all
            row-key="id"
            :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
            :data="organizationList"
            border
            size="mini"
          >
            <el-table-column label="编号" width="80" type="selected">
              <template slot-scope="scope">
                <el-radio v-model="radio" @change="handleUserList" :label="scope.row.id"></el-radio>
              </template>
            </el-table-column>
            <el-table-column label="名称" prop="name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="{row}">
                <el-button type="primary" class="list-mini-btn" @click="handleEdit(row)" title="编辑">编辑</el-button>
                <el-button type="success" class="list-mini-btn" @click="handleUser(row)" title="归属">归属</el-button>
                <el-button type="danger" class="list-mini-btn" @click="handleDelete(row)" title="删除">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
      <el-col :span="16">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>用户信息</span>
          </div>
          <el-table :data="list" border size="mini">
            <el-table-column prop="id" label="ID"></el-table-column>
            <el-table-column prop="userName" label="用户名"></el-table-column>
            <el-table-column prop="name" label="姓名"></el-table-column>
            <el-table-column label="创建日期" width="150" align="center">
              <template slot-scope="scope">
                <i class="el-icon-time" />
                <span>{{ scope.row.creationTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="total>0"
            :total="total"
            :page.sync="listQuery.page"
            :limit.sync="listQuery.limit"
          />
        </el-card>
      </el-col>
    </el-row>

    <!--创建与编辑-->
    <el-dialog :visible.sync="dialogFormVisible" :title="dialogFormTitle" width="30%">
      <el-form
        :model="temp"
        ref="tempRule"
        :rules="rules"
        label-width="80px"
        label-position="right"
      >
        <el-form-item label="上级机构" prop="parentId">
          <el-select v-model="temp.parentId" filterable placeholder="上级">
            <el-option
              v-for="(item,index) in options"
              :key="parseInt(index)"
              :label="item"
              :value="parseInt(index)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="机构名称" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="机构代码" prop="code">
          <el-input v-model="temp.code" />
        </el-form-item>
        <el-form-item label="机构描述" prop="description">
          <el-input
            v-model="temp.description"
            :autosize="{ minRows: 2, maxRows: 4}"
            type="textarea"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="danger" @click="dialogFormVisible=false">取消</el-button>
        <el-button type="primary" @click="saveData">保存</el-button>
      </div>
    </el-dialog>
    <!--归属窗口-->
    <el-dialog :visible.sync="dialogUserVisible" :title="dialogUserTitle" width="30%">
      <el-transfer v-model="organizationUsers" :data="data" filterable :titles="['未归属', '已归属']"></el-transfer>
      <div slot="footer" class="dialog-footer">
        <el-button type="danger" @click="dialogUserVisible=false">取消</el-button>
        <el-button type="primary" @click="SaveTransferData">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getOrganizationList,
  getUserOrganizationList,
  getOrganizationInfo,
  saveOrganizationInfo,
  deleteOrganizationInfo,
  getOrganizationUsers,
  saveOrganizationUser,
  getOrganizationDictionary
} from "@/api/auth/organization";
import { getUserDictionary } from "@/api/auth/user";
import { parseTime } from "@/utils";
import pagination from "@/components/TablePage"; // 分页
export default {
  components: { pagination },
  data() {
    var model = {
      id: null,
      parentId: null,
      name: "",
      code: "",
      description: ""
    };
    return {
      temp: {},
      options: [],
      organizationList: [], //下拉机构
      listQuery: {
        // 分页及搜索参数
        page: 1,
        limit: 20,
        id: undefined
      },
      total: 0,
      list: [], //列表集合
      radio: "",
      data: [],
      organizationUsers: [],
      rules: {
        //表单验证规则
        name: [
          { required: true, trigger: "blur", message: "必填字段" },
          { min: 2, max: 16, message: "长度在2-16个字符", trigger: "blur" }
        ],
        code: [{ required: true, trigger: "blur", message: "必填字段" }]
      },
      dialogFormVisible: false, //是否显示创建编辑窗口
      dialogFormTitle: null, //创建编辑窗口标题
      loadingTableVisible: false,
      dialogUserVisible: false,
      dialogUserTitle: "用户归属"
    };
  },
  created() {
    this.getOrganizations();
  },
  methods: {
    //获取机构列表
    getOrganizations() {
      getOrganizationList().then(response => {
        this.organizationList = response.data;
      });
      getOrganizationDictionary().then(response => {
        this.options = response.data;
      });
    },
    //重置数据模型
    resetTemp() {
      this.temp = this.model;
    },
    //创建事件
    handleCreate() {
      this.resetTemp();
      this.dialogFormTitle = "创建机构";
      this.dialogFormVisible = true;
    },
    //加载用户列表
    handleUserList() {
      this.listQuery.id = this.radio;
      getUserOrganizationList(this.listQuery).then(response => {
        this.list = response.data.items;
        this.total = response.data.total;
      });
    },
    //编辑事件
    handleEdit(row) {
      this.dialogFormTitle = "编辑机构";
      this.dialogFormVisible = true;
      getOrganizationInfo(row.id).then(response => {
        this.temp = response.data;
      });
      this.$nextTick(() => {
        this.$refs["tempRule"].clearValidate();
      });
    },
    //用户归属事件
    handleUser(row) {
      this.dialogUserVisible = true;
      this.dialogUserTitle = "用户归属";
      this.temp.id = row.id;
      this.data = [];
      this.organizationUsers = [];
      getUserDictionary().then(response => {
        for (var key in response.data) {
          this.data.push({
            key: parseInt(key),
            label: response.data[key]
          });
        }
      });
      getOrganizationUsers(id).then(response => {
        this.organizationUsers = response.data;
      });
    },
    //删除事件
    handleDelete(row) {
      this.$confirm("确定删除机构?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          const loading = this.$loading({ text: "正在删除数据" });
          deleteOrganizationInfo(row.id)
            .then(response => {
              loading.close();
              this.$message({
                message: response.message,
                type: response.success ? "success" : "error"
              });
              this.getOrganizations();
            })
            .catch(() => {
              loading.close();
            });
        })
        .catch(err => {
          console.error(err);
        });
    },
    //保存数据
    saveData() {
      this.$refs["tempRule"].validate(valid => {
        if (valid) {
          const loading = this.$loading({ text: "正在保存数据" });
          saveOrganizationInfo(this.temp)
            .then(response => {
              loading.close();
              this.dialogFormVisible = false;
              this.resetTemp();
              this.$message({
                message: response.message,
                type: response.success ? "success" : "error"
              });
              this.getOrganizations();
            })
            .catch(() => {
              loading.close();
            });
        } else return false;
      });
    },
    //保存机构用户
    SaveTransferData() {
      const loading = this.$loading({ text: "正在保存数据" });
      saveOrganizationUser({
        id: this.temp.id,
        userIds: this.organizationUsers
      })
        .then(response => {
          loading.close();
          this.dialogUserVisible = false;
          this.handleUserList(this.temp.id);
          this.$message({
            message: response.message,
            type: response.success ? "success" : "error"
          });
        })
        .catch(() => {
          loading.close();
        });
    },
    //转换上级机构名称
    parseParentName(id) {
      return this.options[id];
    },
    parseInt(value) {
      return parseInt(value);
    }
  }
};
</script>
<style scoped>
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 14px;
  cursor: pointer;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}
</style>